import os
import uuid
import subprocess
import logging
import sqlite3
from datetime import datetime
import time

# 配置
STREAM_CONFIG = {
    "K0123": "rtsp://localhost:8554/video",
}
ffmpeg_path = r"D:\devtools\rtsp\ffmpeg-n4.4.4-6-gd5fa6e3a91-win64-gpl-4.4\bin\ffmpeg"

VIDEO_STORAGE_PATH = "./videos"
DATABASE_PATH = "./events.db"
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def get_db_connection():
    conn = sqlite3.connect(DATABASE_PATH)
    conn.row_factory = sqlite3.Row
    return conn


def process_pending_events():
    """处理所有待处理的事件"""
    logger.info("开始处理待处理事件...")

    while True:
        conn = get_db_connection()
        cursor = conn.cursor()

        # 获取一个待处理的事件
        cursor.execute("SELECT * FROM events WHERE status = 'PENDING' LIMIT 1")
        event = cursor.fetchone()

        if not event:
            conn.close()
            logger.info("没有待处理事件，等待5秒后重试...")
            time.sleep(5)
            continue

        event_dict = dict(event)
        event_id = event_dict["id"]
        stream_id = event_dict["stream_id"]
        event_ts = event_dict["event_ts"]

        logger.info(f"开始处理事件: {event_id}")

        try:
            # 更新状态为处理中
            cursor.execute(
                "UPDATE events SET status = ?, updated_at = ? WHERE id = ?",
                ("PROCESSING", datetime.utcnow().isoformat(), event_id)
            )
            conn.commit()

            # 获取视频流地址
            stream_url = STREAM_CONFIG.get(stream_id)
            if not stream_url:
                raise ValueError(f"Stream ID {stream_id} not found")

            # 生成输出文件名
            output_filename = f"{event_id}.mp4"
            output_path = os.path.join(VIDEO_STORAGE_PATH, output_filename)

            # 计算截取时间
            # start_time = event_ts - 15
            # duration = 30

            # todo 视频太短，强制修改截取时间
            start_time = 0
            duration = 15

            # 使用FFmpeg截取视频
            # cmd = [
            #     ffmpeg_path, "-y",
            #     "-ss", str(start_time),
            #     "-i", stream_url,
            #     "-t", str(duration),
            #     "-c:v", "libx264",
            #     "-c:a", "aac",
            #     output_path
            # ]

            cmd = [
                ffmpeg_path, "-y",
                "-ss", str(start_time),
                "-i", stream_url,
                "-t", str(duration),
                "-c", "copy",
                output_path
            ]

            result = subprocess.run(
                cmd,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True
            )

            if result.returncode != 0:
                logger.error(f"FFmpeg error: {result.stderr}")
                raise RuntimeError(f"Video processing failed: {result.stderr}")

            # 生成视频URL
            video_url = f"http://localhost:8000/videos/{output_filename}"

            # 更新数据库状态为完成
            cursor.execute(
                "UPDATE events SET status = ?, video_url = ?, updated_at = ? WHERE id = ?",
                ("COMPLETED", video_url, datetime.utcnow().isoformat(), event_id)
            )
            conn.commit()
            logger.info(f"事件 {event_id} 处理完成: {video_url}")

        except Exception as e:
            logger.error(f"处理事件 {event_id} 失败: {str(e)}")
            # 更新数据库状态为失败
            cursor.execute(
                "UPDATE events SET status = ?, updated_at = ? WHERE id = ?",
                ("FAILED", datetime.utcnow().isoformat(), event_id)
            )
            conn.commit()

        finally:
            conn.close()


if __name__ == "__main__":
    try:
        process_pending_events()
    except KeyboardInterrupt:
        logger.info("手动处理器已停止")
